//! 主题配置模块
//! 负责加载和解析Material Design 3主题配置文件
//! 创建时间：2025-10-17 作者：AI助手 目的：实现基于JSON配置文件的主题系统

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;

// 导入主题相关枚举
use crate::Theme;
use crate::ThemeMode;

/// 默认描述
fn default_description() -> String {
    "Material Design 3 Theme Configuration".to_string()
}

/// 默认种子颜色
fn default_seed() -> String {
    "#6750A4".to_string() // 默认紫色作为种子颜色
}

/// Material Design 3主题配置结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialThemeConfig {
    #[serde(default = "default_description")]
    pub description: String,
    #[serde(default = "default_seed")]
    pub seed: String,
    #[serde(default)]
    pub core_colors: CoreColors,
    #[serde(default)]
    pub extended_colors: Vec<ExtendedColor>,
    pub schemes: ThemeSchemes,
    #[serde(default)]
    pub palettes: ThemePalettes,
}

/// 核心颜色配置
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CoreColors {
    pub primary: String,
}

/// 扩展颜色配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtendedColor {
    pub name: String,
    pub color: String,
    pub description: String,
    pub harmonized: bool,
}

/// 主题方案配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThemeSchemes {
    pub light: ColorScheme,
    #[serde(rename = "light-medium-contrast")]
    pub light_medium_contrast: ColorScheme,
    #[serde(rename = "light-high-contrast")]
    pub light_high_contrast: ColorScheme,
    pub dark: ColorScheme,
    #[serde(rename = "dark-medium-contrast")]
    pub dark_medium_contrast: ColorScheme,
    #[serde(rename = "dark-high-contrast")]
    pub dark_high_contrast: ColorScheme,
}

/// 颜色方案配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColorScheme {
    #[serde(rename = "primary")]
    pub primary: String,
    #[serde(rename = "surfaceTint")]
    pub surface_tint: String,
    #[serde(rename = "onPrimary")]
    pub on_primary: String,
    #[serde(rename = "primaryContainer")]
    pub primary_container: String,
    #[serde(rename = "onPrimaryContainer")]
    pub on_primary_container: String,
    #[serde(rename = "secondary")]
    pub secondary: String,
    #[serde(rename = "onSecondary")]
    pub on_secondary: String,
    #[serde(rename = "secondaryContainer")]
    pub secondary_container: String,
    #[serde(rename = "onSecondaryContainer")]
    pub on_secondary_container: String,
    #[serde(rename = "tertiary")]
    pub tertiary: String,
    #[serde(rename = "onTertiary")]
    pub on_tertiary: String,
    #[serde(rename = "tertiaryContainer")]
    pub tertiary_container: String,
    #[serde(rename = "onTertiaryContainer")]
    pub on_tertiary_container: String,
    #[serde(rename = "error")]
    pub error: String,
    #[serde(rename = "onError")]
    pub on_error: String,
    #[serde(rename = "errorContainer")]
    pub error_container: String,
    #[serde(rename = "onErrorContainer")]
    pub on_error_container: String,
    #[serde(rename = "background")]
    pub background: String,
    #[serde(rename = "onBackground")]
    pub on_background: String,
    #[serde(rename = "surface")]
    pub surface: String,
    #[serde(rename = "onSurface")]
    pub on_surface: String,
    #[serde(rename = "surfaceVariant")]
    pub surface_variant: String,
    #[serde(rename = "onSurfaceVariant")]
    pub on_surface_variant: String,
    #[serde(rename = "outline")]
    pub outline: String,
    #[serde(rename = "outlineVariant")]
    pub outline_variant: String,
    #[serde(rename = "shadow")]
    pub shadow: String,
    #[serde(rename = "scrim")]
    pub scrim: String,
    #[serde(rename = "inverseSurface")]
    pub inverse_surface: String,
    #[serde(rename = "inverseOnSurface")]
    pub inverse_on_surface: String,
    #[serde(rename = "inversePrimary")]
    pub inverse_primary: String,
    #[serde(rename = "primaryFixed")]
    pub primary_fixed: String,
    #[serde(rename = "onPrimaryFixed")]
    pub on_primary_fixed: String,
    #[serde(rename = "primaryFixedDim")]
    pub primary_fixed_dim: String,
    #[serde(rename = "onPrimaryFixedVariant")]
    pub on_primary_fixed_variant: String,
    #[serde(rename = "secondaryFixed")]
    pub secondary_fixed: String,
    #[serde(rename = "onSecondaryFixed")]
    pub on_secondary_fixed: String,
    #[serde(rename = "secondaryFixedDim")]
    pub secondary_fixed_dim: String,
    #[serde(rename = "onSecondaryFixedVariant")]
    pub on_secondary_fixed_variant: String,
    #[serde(rename = "tertiaryFixed")]
    pub tertiary_fixed: String,
    #[serde(rename = "onTertiaryFixed")]
    pub on_tertiary_fixed: String,
    #[serde(rename = "tertiaryFixedDim")]
    pub tertiary_fixed_dim: String,
    #[serde(rename = "onTertiaryFixedVariant")]
    pub on_tertiary_fixed_variant: String,
    #[serde(rename = "surfaceDim")]
    pub surface_dim: String,
    #[serde(rename = "surfaceBright")]
    pub surface_bright: String,
    #[serde(rename = "surfaceContainerLowest")]
    pub surface_container_lowest: String,
    #[serde(rename = "surfaceContainerLow")]
    pub surface_container_low: String,
    #[serde(rename = "surfaceContainer")]
    pub surface_container: String,
    #[serde(rename = "surfaceContainerHigh")]
    pub surface_container_high: String,
    #[serde(rename = "surfaceContainerHighest")]
    pub surface_container_highest: String,
}

/// 调色板配置
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ThemePalettes {
    pub primary: HashMap<String, String>,
    pub secondary: HashMap<String, String>,
    pub tertiary: HashMap<String, String>,
    pub neutral: HashMap<String, String>,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub neutral_variant: HashMap<String, String>,
}

/// 主题管理器
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct ThemeManager {
    pub config: MaterialThemeConfig,
    pub current_theme: String,
    pub current_mode: String,
}

#[allow(dead_code)]
impl ThemeManager {
    /// 从文件加载主题配置
    pub fn load_from_file(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let content = fs::read_to_string(path)?;
        let config: MaterialThemeConfig = serde_json::from_str(&content)?;
        
        Ok(Self {
            config,
            current_theme: "default".to_string(),
            current_mode: "light".to_string(),
        })
    }
    
    /// 获取当前颜色方案
    pub fn get_current_scheme(&self) -> &ColorScheme {
        match self.current_mode.as_str() {
            "light" => &self.config.schemes.light,
            "light-medium-contrast" => &self.config.schemes.light_medium_contrast,
            "light-high-contrast" => &self.config.schemes.light_high_contrast,
            "dark" => &self.config.schemes.dark,
            "dark-medium-contrast" => &self.config.schemes.dark_medium_contrast,
            "dark-high-contrast" => &self.config.schemes.dark_high_contrast,
            _ => &self.config.schemes.light,
        }
    }
    
    /// 设置主题模式
    pub fn set_mode(&mut self, mode: &str) {
        self.current_mode = mode.to_string();
    }
    
    /// 设置主题颜色
    pub fn set_theme(&mut self, theme: &str) {
        self.current_theme = theme.to_string();
    }
    
    /// 根据主题模式获取颜色方案
    pub fn get_color_scheme(&self, theme_mode: ThemeMode) -> Result<&ColorScheme, Box<dyn std::error::Error>> {
        match theme_mode {
            ThemeMode::Light => Ok(&self.config.schemes.light),
            ThemeMode::Dark => Ok(&self.config.schemes.dark),
        }
    }
    
    /// 获取默认颜色方案（亮色模式）
    pub fn get_default_scheme(&self, theme_mode: ThemeMode) -> &ColorScheme {
        match theme_mode {
            ThemeMode::Light => &self.config.schemes.light,
            ThemeMode::Dark => &self.config.schemes.dark,
        }
    }
    
    /// 从十六进制颜色字符串转换为egui::Color32
    pub fn hex_to_color32(hex: &str) -> Result<egui::Color32, Box<dyn std::error::Error>> {
        let hex = hex.trim_start_matches('#');
        
        if hex.len() != 6 {
            return Err("Invalid hex color format".into());
        }
        
        let r = u8::from_str_radix(&hex[0..2], 16)?;
        let g = u8::from_str_radix(&hex[2..4], 16)?;
        let b = u8::from_str_radix(&hex[4..6], 16)?;
        
        Ok(egui::Color32::from_rgb(r, g, b))
    }
    
    /// 获取主色调
    pub fn get_primary_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        let color_value = match theme {
            Theme::Blue => &scheme.primary,
            Theme::Green => &scheme.secondary,
            Theme::Orange => &scheme.tertiary,
            Theme::Purple => &scheme.primary, // 使用primary作为紫色主题的基础
        };
        
        ThemeManager::hex_to_color32(color_value).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取主容器色
    pub fn get_primary_container_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        let color_value = match theme {
            Theme::Blue => &scheme.primary_container,
            Theme::Green => &scheme.secondary_container,
            Theme::Orange => &scheme.tertiary_container,
            Theme::Purple => &scheme.primary_container, // 使用primary_container作为紫色主题的基础
        };
        
        ThemeManager::hex_to_color32(color_value).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取次色调
    pub fn get_secondary_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        ThemeManager::hex_to_color32(&scheme.secondary).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取次容器色
    pub fn get_secondary_container_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        ThemeManager::hex_to_color32(&scheme.secondary_container).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取第三色调
    pub fn get_tertiary_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        let color_value = match theme {
            Theme::Blue => &scheme.tertiary,
            Theme::Green => &scheme.tertiary,
            Theme::Orange => &scheme.secondary,
            Theme::Purple => &scheme.tertiary,
        };
        
        ThemeManager::hex_to_color32(color_value).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取第三容器色
    pub fn get_tertiary_container_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        let color_value = match theme {
            Theme::Blue => &scheme.tertiary_container,
            Theme::Green => &scheme.tertiary_container,
            Theme::Orange => &scheme.secondary_container,
            Theme::Purple => &scheme.tertiary_container,
        };
        
        ThemeManager::hex_to_color32(color_value).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取表面色
    pub fn get_surface_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        ThemeManager::hex_to_color32(&scheme.surface).unwrap_or_else(|_| self.get_default_surface_color())
    }
    
    /// 获取表面变体色
    pub fn get_surface_variant_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        ThemeManager::hex_to_color32(&scheme.surface_variant).unwrap_or_else(|_| self.get_default_surface_color())
    }
    
    /// 获取表面上的文本颜色
    pub fn get_on_surface_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        ThemeManager::hex_to_color32(&scheme.on_surface).unwrap_or_else(|_| self.get_default_text_color())
    }
    
    /// 获取表面变体上的文本颜色
    pub fn get_on_surface_variant_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        ThemeManager::hex_to_color32(&scheme.on_surface_variant).unwrap_or_else(|_| self.get_default_text_color())
    }
    
    /// 获取错误色
    pub fn get_error_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        ThemeManager::hex_to_color32(&scheme.error).unwrap_or_else(|_| self.get_default_error_color())
    }
    
    /// 获取轮廓色
    pub fn get_outline_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        ThemeManager::hex_to_color32(&scheme.outline).unwrap_or_else(|_| self.get_default_outline_color())
    }
    
    /// 获取背景色
    pub fn get_background_color(&self) -> Result<egui::Color32, Box<dyn std::error::Error>> {
        let scheme = self.get_current_scheme();
        ThemeManager::hex_to_color32(&scheme.background)
    }
    
    /// 获取表面容器最低色
    pub fn get_surface_container_lowest_color(&self) -> Result<egui::Color32, Box<dyn std::error::Error>> {
        let scheme = self.get_current_scheme();
        ThemeManager::hex_to_color32(&scheme.surface_container_lowest)
    }
    
    /// 获取默认颜色（用于错误处理）
    fn get_default_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(62, 105, 0) // 备用绿色作为默认主题色
    }
    
    /// 获取默认表面颜色（用于错误处理）
    fn get_default_surface_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(247, 251, 234) // 备用浅绿背景色
    }
    
    /// 获取默认文本颜色（用于错误处理）
    fn get_default_text_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(25, 29, 19) // 备用深色文本
    }
    
    /// 获取默认错误颜色（用于错误处理）
    fn get_default_error_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(186, 26, 26) // 备用红色错误色
    }
    
    /// 获取默认轮廓颜色（用于错误处理）
    fn get_default_outline_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(114, 122, 102) // 备用灰色轮廓
    }
    
    /// 获取表面容器高色
    pub fn get_surface_container_high_color(&self) -> Result<egui::Color32, Box<dyn std::error::Error>> {
        let scheme = self.get_current_scheme();
        ThemeManager::hex_to_color32(&scheme.surface_container_high)
    }
    
    /// 获取表面容器最高色
    pub fn get_surface_container_highest_color(&self) -> Result<egui::Color32, Box<dyn std::error::Error>> {
        let scheme = self.get_current_scheme();
        ThemeManager::hex_to_color32(&scheme.surface_container_highest)
    }
}

/// 默认主题管理器实例
pub fn create_default_theme_manager() -> Result<ThemeManager, Box<dyn std::error::Error>> {
    ThemeManager::load_from_file("docs/material-theme.json")
}